# Create your views here.
from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson
from house.models import Type, Trade
from house.forms import AddTradeForm, UploadImageForm
from house.manager import setUserImage

TRADE_NUM_OF_PAGE = 20

def index(request):
    return render(request, "house/index.html", {'types':Type.objects.all()})


def latest_trade(request, page_num):
    _pagenum = int(page_num)
    trade_qs = Trade.objects.filter(status=Trade.STATUS_NORMAL)
    paginator = Paginator(trade_qs, TRADE_NUM_OF_PAGE)

    try:
        trade_list = paginator.page(page_num)
    except EmptyPage:
        trade_list = paginator.page(paginator.num_pages)

    return render(request, "house/house_list.html", {'trade_list': trade_list, 'page':paginator})


def trade_detail(request, trade_id):
    _tradeid = int(trade_id)
    trade = get_object_or_404(Trade, pk=_tradeid)
    trade.reads = trade.reads + 1
    trade.save()
    return render(request, "house/house_detail.html", {"trade": trade}) 


def trade_list(request, type_id, page_num):
    _typeid = int(type_id)
    _pagenum = int(page_num)

    ttype = get_object_or_404(Type, pk=_typeid)
    trade_qs = Trade.objects.filter(status=Trade.STATUS_NORMAL, ttype_id = _typeid)

    paginator = Paginator(trade_qs, TRADE_NUM_OF_PAGE)

    try:
        trade_list = paginator.page(page_num)
    except EmptyPage:
        trade_list = paginator.page(paginator.num_pages)

    return render(request, "house/house_list.html", {'trade_list': trade_list, 'page':paginator,'ttype':ttype})


@login_required
def add_trade(request):
    if request.method == 'GET':
        f = AddTradeForm()
        return render(request, "house/add_trade.html", {"form":f})
        
    f = AddTradeForm(request.POST)
    if f.is_valid():
        trade = f.save(False)
        trade.user = request.user
        trade.save()

        for imgname in request.POST.getlist('userimg', []):
            setUserImage(request.user, imgname, trade)

        return redirect("/house/trade/%d/"%(trade.id))

    else:
        return render(request, "house/add_trade.html", {"form":f})


